<?php

namespace app\api\controller;

use think\Controller;
use app\api\model\UserModel;
use think\Session;

class User extends Controller {
    function login() {
        $username = input('get.username');
        $password = input('get.password');
        $model = new  UserModel();
        $result = $model->login($username, $password);
        if ($result) {
            return json(['userid' => $result['userid'],'nickname' => $result['nickname'],'picture' => $result['picture']]);
        } else {
            return json(['userid' => -1]);
        }
    }

    function register() {
        $username = input('get.username');
        $password = input('get.password');
        $address = input('get.address');
        $phone = input('get.phone');

        $phone = isset($phone)?$phone:"";
        $gender = input('get.gender');
        $gender = isset($gender)?$gender:"男";
        $model = new  UserModel();

        $result = $model->register($username, $password, $address, $phone, $gender);

        return json(['userid' => $result]);
    }



function getpicture() {
    $userid = input('get.userid');

    $model = new UserModel();
    $result = $model->getpicture($userid);
    return json($result);
}

function gameenroll() {

    $userid = input('get.userid');
    $gameid = input('get.gameid');

    $model = new UserModel();
    $result = $model->gameenroll($userid, $gameid);
    return json($result);


}

function repassword() {
    $userid = input('get.userid');

    $oldpassword = input('get.oldpassword');
    $newpassword = input('get.newpassword');


    $model = new UserModel();
    $result = $model->repassword($userid, $oldpassword, $newpassword);
    return json($result);


}

/*function updatenickname() {
    $userid = input('get.userid');
    $nickname = input('get.nickname');


    $model = new UserModel();
    $result = $model->updateNickname($userid, $nickname);
    return json($result);

}*/

function updateuser(){
    $userid = input('get.userid');
    $nickname = input('get.nickname');
    $password = input('get.password');
    $address = input('address');
    $phone = input('phone');

    $model = new UserModel();
    $result = $model->updateUser($userid,$nickname,$password,$address,$phone);
    return json($result);
//    return json(['success'=>$result]);
}

function getuser(){
    $userid = input('get.userid');
    $model = new UserModel();
    $result = $model->getuser($userid);
    return json($result);
}


function updateavatar() {

    $userid = input('post.userid');

    $file = request()->file('image');
    if ($file) {
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if ($info) { //上传成功
            $model = new UserModel();
            $result = $model->updateAvatar($userid, $info->getSaveName());
            return json($result);
        } else {
            // 上传失败获取错误信息
            return json(['error' => $file->getError()]);
        }
    }
    return "ok";

}
}